#include "BdbBase.h"
CBdbBase::CBdbBase(void)
{	
    system("rm -rf dbfile");
    system("mkdir dbfile");
	//DB_ENV *m_p_env = NULL;
	//DB *m_p_db= NULL;
	int i_ret;

	i_ret = db_env_create(&m_p_env, 0);
	print_error(i_ret);

	u_int32_t env_flags;
	env_flags = DB_CREATE | DB_INIT_MPOOL;

	i_ret = m_p_env->open(m_p_env, DBLOCATE,env_flags, 0);
	print_error(i_ret);

	i_ret = db_create(&m_p_db,m_p_env,0);
	print_error(i_ret);

	i_ret = m_p_db->open(m_p_db,NULL,DATABASE,NULL,
			DB_BTREE,DB_CREATE,0664);
	print_error(i_ret);
}

CBdbBase::~CBdbBase(void)
{
	if (m_p_db != NULL)
	{
		m_p_db->close(m_p_db, 0);
	}
	if (m_p_env != NULL)
	{
		m_p_env->close(m_p_env, 0);
	}
    system("rm -rf dbfile");
}
void CBdbBase::print_error(int in_i_ret)
{
	if(0 != in_i_ret)
	{
		printf("ERROR:%s\n",db_strerror(in_i_ret));
	}
}
void CBdbBase::init_DBT(DBT* key,DBT* value)
{
	memset(key,0,sizeof(DBT));
	memset(value,0,sizeof(DBT));
}

int CBdbBase::insert(int in_i_key,char* in_pc_value)
{
	DBT key,data;
	init_DBT(&key,&data);
	int k = in_i_key;

	key.size = sizeof(int);
	key.data = &k;

	data.size = VALUE_SIZE;
    data.data = in_pc_value;
	//put data
	int i_ret = m_p_db->put(m_p_db,NULL,&key,&data,
			DB_NOOVERWRITE);

	return i_ret;
}
int CBdbBase::get(int in_i_key,char *out_pc_value)
{
	DBT key,data;
	init_DBT(&key,&data);

	int k = in_i_key;
	key.size = sizeof(int);
	key.data = &k;

	int i_ret = m_p_db->get(m_p_db,NULL,&key,&data,0);

	if(NULL == data.data)
	{
        printf("nothing get [%d]\n",i_ret);
        print_error(i_ret);
		return -1;
	}

	memcpy(out_pc_value,data.data,VALUE_SIZE);
	this->del(in_i_key);

	return 0;
}
int CBdbBase::del(int in_i_key)
{
	DBT key,data;
	init_DBT(&key,&data);

	key.size = sizeof(int);
	key.data = &in_i_key;

	int i_ret = m_p_db->del(m_p_db,NULL,&key,0);

	return i_ret;
}
